//
//  EmoticonToolbar.swift
//  EmoticonKeyboard
//
//  Created by liii on 16/8/14.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit

//private let baseTag = 1000

class EmoticonToolbar: UIStackView {
    
    
    // 记录当前被点击的按钮
    var currentButton: UIButton?
    
    // 此闭包用于实现工具条按钮被点击后，让collectionView滚动
    var emoticonDidClick: ((index: Int) -> ())?
    
    // 此闭包用于实现collectionView滚动停止后，让按钮改变状态
    var changeButton: ((index: Int) -> ())?

    init() {
        super.init(frame: CGRectZero)
        
        // 设置StackView的布局方式
        axis = .Horizontal          // 横向布局
        distribution = .FillEqually // 等分填充
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        let packages = EmoticonManager.sharedEmotionManager.packages
        setToolbarButton(packages)
        
        // 给闭包赋值，当滑动collectionView的时候调用
        changeButton = {(index: Int) -> () in
            let btn = self.viewWithTag(index + baseTag) as! UIButton
            self.setButton(btn)
        }
    }
    
    // 设置toolbar中的按钮
    private func setToolbarButton(packages: [EmoticonPackages]) {
        var index = 0
        for p in packages {
            var imageName = "compose_emotion_table_mid"
            if index == 0 {
                imageName = "compose_emotion_table_left"
            } else if index == packages.count - 1 {
                imageName = "compose_emotion_table_right"
            }
            addSubButtons(p.name ?? "", backImage: imageName, type: index)
            index++
        }
    }
    
    // 给工具条添加按钮
    private func addSubButtons(title: String, backImage: String, type: Int) {
        let btn = UIButton()
        // 文字
        btn.setTitle(title, forState: .Normal)
        
        // 文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        
        // 背景图片
        btn.setBackgroundImage(UIImage(named: backImage + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImage + "_selected"), forState: .Selected)
        
        // 记录按钮
        btn.tag = baseTag + type
        
        // 点击事件
        btn.addTarget(self, action: "itemDidClick:", forControlEvents: .TouchUpInside)
        
        // 默认选择第一个按钮
        if type == 0 {
            btn.selected = true
            currentButton = btn
        }
        
        // 给UIStackView添加控件
        addArrangedSubview(btn)
    }
    
    @objc private func itemDidClick(btn: UIButton) {
    
        setButton(btn)
        // 调用闭包
        emoticonDidClick?(index: btn.tag - baseTag)
    }
    
    // 记录并设置按钮
    private func setButton(btn: UIButton) {
        // 取消上一个按钮的选中状态
        currentButton?.selected = false
        // 记录本次被点击的按钮
        currentButton = btn
        // 并设置为选中状态
        btn.selected = true
    }
    
}


